package com.swind.fast.modules.app.space.rent.service.impl;

import com.swind.fast.common.util.oConvertUtils;

import com.swind.fast.modules.app.space.rent.entity.SpaceContract;
import com.swind.fast.modules.app.space.rent.entity.SpaceContractBill;
import com.swind.fast.modules.app.space.rent.mapper.SpaceContractBillMapper;
import com.swind.fast.modules.app.space.rent.service.ISpaceContractBillService;
import com.swind.fast.modules.app.space.rent.model.SpaceAnnouncementModel;

import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.ApplicationContext;

import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.hutool.core.date.DateBetween;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;

import javax.annotation.Resource;

import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;

/**
 * @Description: 项目
 * @Author: swind
 * @Date:   2021-11-20
 * @Version: V1.0
 */
@Slf4j
@Service
public class SpaceContractBillServiceImpl extends ServiceImpl<SpaceContractBillMapper, SpaceContractBill> implements ISpaceContractBillService {

    public String getMonthData() {
        // DateTime cdate = new DateTime()
        String cmonth = new DateTime().toDateStr().substring(0, 7);
        String nmonth = DateUtil.nextMonth().toDateStr().substring(0, 7);

        // QueryWrapper<SpaceContractBill> queryWrapper = new QueryWrapper<SpaceContractBill>().select("sum(price) as total").like("start_date", cmonth + "%");
        QueryWrapper<SpaceContractBill> queryWrapper = new QueryWrapper<SpaceContractBill>().select("ifnull(sum(price), 0) as total").like("remind_date", cmonth + "%");
        Map<String, Object> obj = this.getMap(queryWrapper);
        // if (oConvertUtils.isEmpty(obj.get("total"))) {
        //     log.info("obj: {}", obj);
        //     obj.put("total", "0")
        //     log.info("obj: {}", obj);
        // }
        log.info("obj: {}", obj);

        // queryWrapper = new QueryWrapper<SpaceContractBill>().select("sum(price) as total").like("start_date", nmonth + "%");
        queryWrapper = new QueryWrapper<SpaceContractBill>().select("ifnull(sum(price), 0) as total").like("remind_date", nmonth + "%");
        Map<String, Object> obj2 = this.getMap(queryWrapper);
        // log.info("obj2: {}", obj2);

        // 获取已逾期数据
        DateTime cdate = new DateTime();
        cmonth = cdate.toDateStr();
        queryWrapper = new QueryWrapper<SpaceContractBill>().select("contract_id").ne("status", "1").lt("end_date", cmonth);
        List<SpaceContractBill> tlist = this.list(queryWrapper);
        List<String> listIds = tlist.stream().map(SpaceContractBill::getContractId).distinct().collect(Collectors.toList());
        log.info("listIds: {}, {}", cmonth, listIds);

        // queryWrapper = new QueryWrapper<SpaceContractBill>().select("ifnull(total(id), 0) as total").like("remind_date", nmonth + "%");
        // Map<String, Object> obj3 = this.getMap(queryWrapper);

        return obj.get("total").toString() + "," + obj2.get("total").toString() + "," + listIds.size();
    }

    public void saveBatchBill(SpaceContract contract) {
        Integer priceByMonth = oConvertUtils.getInt(contract.getPrice());
        Integer period = oConvertUtils.getInt(contract.getPeriod().substring(0, 1));
        if (contract.getPeriod().equals("12m")) {
            period = 12;
        }
        String price = String.valueOf(priceByMonth * period);

        Date startDate = Convert.toDate(contract.getStartDate());
        Date endDate = Convert.toDate(contract.getEndDate());
        DateBetween between = new DateBetween(startDate, endDate);
        Integer months = Convert.toInt(between.betweenMonth(true));
        Integer mod = months % period;
        Integer times = months / period;
        log.info("times: {}, mod: {}", times, mod);
        DateTime pstartDate = DateUtil.date(startDate);
        DateTime nextDate;
        DateTime remindDate;
        List<SpaceContractBill> bills = new ArrayList<SpaceContractBill>();
        for (int i = 0; i < times; i++) {
            nextDate = DateUtil.offsetMonth(pstartDate, period);
            remindDate = DateUtil.offsetDay(pstartDate, -15);
            log.info("nextDate: {}", nextDate);
            SpaceContractBill bill = SpaceContractBill.builder()
                                    .contractId(contract.getId())
                                    .customerId(contract.getCustomerId())
                                    .roomId(contract.getRoomId())
                                    .price(price)
                                    .startDate(pstartDate.toDateStr())
                                    .endDate(nextDate.toDateStr())
                                    .remindDate(remindDate.toDateStr())
                                    .build();
            log.info("bill: {}", bill);
            bills.add(bill);
            pstartDate = nextDate;
        }

        if (mod != 0) {
            nextDate = DateUtil.offsetMonth(pstartDate, mod);
            log.info("nextDate: {}", nextDate);

            price = String.valueOf(priceByMonth * mod);

            SpaceContractBill bill = SpaceContractBill.builder()
                                    .contractId(contract.getId())
                                    .customerId(contract.getCustomerId())
                                    .roomId(contract.getRoomId())
                                    .price(price)
                                    .startDate(pstartDate.toDateStr())
                                    .endDate(nextDate.toDateStr())
                                    .build();
            log.info("bill: {}", bill);
            bills.add(bill);
        }

        this.saveBatch(bills);
    }

    // @Override
    // public List<SpaceAnnouncementModel> getSpaceAnnouncementList( @Param("spaceAnnouncementModel") SpaceAnnouncementModel spaceAnnouncementModel) {
    //      return page.setRecords(this.baseMapper.getSpaceAnnouncementList(page, spaceAnnouncementModel));
    // }

    @Override
    public List<SpaceAnnouncementModel> getSpaceAnnouncementList(@Param("spaceAnnouncementModel") SpaceAnnouncementModel spaceAnnouncementModel) {
        return this.baseMapper.getSpaceAnnouncementList(spaceAnnouncementModel);
    }
}
